package com.jinsi.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.jinsi.pojo.User;
import com.jinsi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
/*
密码加密
MD5 加密

 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private DefaultKaptcha captchaProducer ;

    // 获取验证码图片
    @RequestMapping("/kaptcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = captchaProducer.createText();
        // 将验证码文字存入session
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        //向客户端写出
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }



    @ResponseBody
    @RequestMapping("/login")
    public Map<String,String> login(String captcha,String username,
                                    String password,HttpSession session){


        Map<String,String> map = new HashMap<>();
// 从session获取图片上验证码文字
       String scaptcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
//
//       if(!captcha.equals(scaptcha)){ // 输入的文字与图片上文字不一致
//           // 验证码错误
//           map.put("state","302");
//           map.put("msg","验证码错误");
//
//            return map;
//       }

        User user = userService.getUserByNameAndPwd(username, null);
        if(user != null){

            // 验证密码
            String oldpwd = user.getPassword(); // 数据库的密码
            // 使用username作为盐值  -- 再次加密生成密码
            String newpwd = DigestUtils.md5DigestAsHex((username + password).getBytes());
            // 比较数据库密码与再次生成的密码，一致则密码正确，否则不正确
            if(oldpwd.equals(newpwd)){
                // 登录成功
                // user 存入session中
                session.setAttribute("loginuser",user);

                map.put("state","200");
                map.put("msg","登录成功");
                map.put("userid",user.getId()+"");
                map.put("uname",user.getUsername());
            }else{
                // 密码错误
                map.put("state","301");
                map.put("msg","密码错误");
            }

        }else{
            // 登录失败，用户名不存在
            map.put("state","300");
            map.put("msg","用户名不存在");

        }

        return map;
    }

}
